import { router, Redirect } from 'expo-router';
import { type FC, useEffect } from 'react';
import { useMount, useMemoizedFn } from 'ahooks';
import * as SplashScreen from 'expo-splash-screen';
import { waiting } from '@/utils/helper';

type RootRedirectProps = {
  logined: boolean;
  path: string;
  children?: (logined: boolean) => any;
}

/**
 * 路由黑名单，表示在登录状态下会跳转入
 * posts 页面的路由
*/
const blackList = ['/', '/signin'];

const RootRedirect: FC<RootRedirectProps> = (props) => {
  const { logined, path } = props;

  const openApp = useMemoizedFn(async () => {
    await waiting(300);
    SplashScreen.hideAsync();
  });

  const onAuth = useMemoizedFn(() => {
    if (blackList.find(v => v === path)) {
      // 登录状态
      if (logined) {
        router.dismissTo('/posts');
      }
    } else {
      // 非登录状态
      if (!logined) {
        router.dismissTo('/');
      }
    }
  });

  useMount(openApp);
  useEffect(onAuth, [path, logined]);
  
  return props.children?.(logined);
}

export default RootRedirect;